package com.wbf.demo.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wbf.demo.security.exception.ErrorMsg;
import com.wbf.demo.util.ServletTool;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.session.InvalidSessionStrategy;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * session无效时处理策略
 * @author fal
 */
public class JsonInvalidSessionStrategy implements InvalidSessionStrategy{
	private final ObjectMapper objectMapper;
	private final ErrorMsg unauthenticatedMsg;

	public JsonInvalidSessionStrategy(ObjectMapper objectMapper, ErrorMsg unauthenticatedMsg){
		this.objectMapper = objectMapper;
		this.unauthenticatedMsg = unauthenticatedMsg;
	}
	
	@Override
	public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		response.setStatus(HttpStatus.UNAUTHORIZED.value());
		ServletTool.writeJSONStr(response, objectMapper.writeValueAsString(unauthenticatedMsg));
	}

}
